package com.agileboot.attendance.domain.settlement.utils;

import com.agileboot.attendance.domain.settlement.mapper.AttSettlementMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 结算单号生成器
 */
@Component
@RequiredArgsConstructor
public class SettlementBillNoGenerator {

    private final AttSettlementMapper settlementMapper;
    private static final String PREFIX = "JS";
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");

    /**
     * 生成结算单号
     * 格式：JS + 年月 + 4位流水号
     * 示例：JS2024030001
     * 对应表字段：settlement_code
     */
    public String generate() {
        LocalDate now = LocalDate.now();
        String yearMonth = now.format(FORMATTER);
        
        // 查询当月最大流水号
        String prefix = PREFIX + yearMonth;
        String maxBillNo = settlementMapper.getMaxBillNoByPrefix(prefix);
        
        // 生成新的流水号
        int sequence;
        if (maxBillNo == null) {
            sequence = 1;
        } else {
            String sequenceStr = maxBillNo.substring(maxBillNo.length() - 4);
            sequence = Integer.parseInt(sequenceStr) + 1;
        }
        
        // 格式化流水号为4位数字
        return String.format("%s%04d", prefix, sequence);
    }
} 